package top100.dynamic;

import java.util.Scanner;

/**
 * @Author ZhangCuirong
 * @Date 2025/7/17 11:00
 * @description: 01 背包
 * 有n件物品和一个最多能背重量为w 的背包。第i件物品的重量是weight[i]，得到的价值是value[i] 。每件物品只能用一次，求解将哪些物品装入背包里物品价值总和最大。
 */
/*
6 1
2 2 3 1 5 2
2 3 1 5 4 3
 */

public class Main1 {
    public int bag(int[] weight, int[] value, int w) {
        int[][] dp = new int[weight.length][w + 1];

        for (int j = weight[0]; j <= w; j++) {
            dp[0][j] = value[0];
        }
        for (int i = 1; i < weight.length; i++) {
            for (int j = 0; j <= w; j++) {
                if (j >= weight[i]) {
                    dp[i][j] = Math.max(dp[i - 1][j - weight[i]] + value[i], dp[i - 1][j]);
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        return dp[weight.length - 1][w];
    }
    public int bag2(int[] weight, int[] value, int w){
        int[][] dp = new int[weight.length][w + 1];

        for (int j = weight[0]; j <= w; j++) {
            dp[0][j] = value[0];
        }
        for (int j = 0; j <= w; j++) {
            for (int i = 1; i < weight.length; i++) {
                if (j >= weight[i]) {
                    dp[i][j] = Math.max(dp[i - 1][j - weight[i]] + value[i], dp[i - 1][j]);
                } else {
                    dp[i][j] = dp[i - 1][j];
                }
            }
        }
        return dp[weight.length - 1][w];
    }
    public int bag3(int[] weight, int[] value, int w){
        //倒序遍历是为了保证物品i只被放入一次！。但如果一旦正序遍历了，那么物品0就会被重复加入多次！
        int[] dp = new int[w + 1];

        for (int j = weight[0]; j <= w; j++) {
            dp[j] = value[0];
        }
        for (int i = 1; i < weight.length; i++) {
            for (int j = w; j >=weight[i]; j--) {
                if (j >= weight[i]) {
                    dp[j] = Math.max(dp[j - weight[i]] + value[i], dp[j]);
                }
            }
        }
        return dp[w];
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int M = sc.nextInt();
        int N = sc.nextInt();
        int[] weight = new int[M + 1];
        int[] value = new int[M + 1];
        for (int i = 0; i < M; i++) {
            weight[i] = sc.nextInt();
        }
        for (int i = 0; i < M; i++) {
            value[i] = sc.nextInt();
        }
        Main1 main = new Main1();
        int res = main.bag(weight, value, N);
        System.out.println(res);
    }
}
